/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: ObjectInputStreamLogCollector.java 333 2007-02-04 18:49:59Z jack.rybicki $
 */
package logmatcher.collectors;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import org.apache.commons.lang.UnhandledException;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Reads messages from ObjectInputStream and puts them to the configured LogBuffer.
 *
 * @version $Revision: 333 $
*/
public class ObjectInputStreamLogCollector extends CollectorSkeleton {
    //~ Static fields/initializers -------------------------------------------------------------------------------------

    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(ObjectInputStreamLogCollector.class);

    //~ Instance fields ------------------------------------------------------------------------------------------------

    /** Source of messages. */
    private ObjectInputStream iStream;

 
	/**
	 * Stop collector.
	 *
	 * @throws IOException in case of problem while closing stream.
	 */
	public void stop() throws IOException {
	    super.stop();
	    iStream.close();
	}

    //~ Constructors ---------------------------------------------------------------------------------------------------

/**
     * Creates a new SocketLogCollector object.
     *
     * @param iStream input stream, message objects will be read from it.
     *
     * @throws IOException in case of incorrect stream type, ObjectInputStream is expected.
     * @see java.io.ObjectInputStream#ObjectInputStream(InputStream)
     */
    public ObjectInputStreamLogCollector(InputStream iStream)
        throws IOException {
        this.iStream = new ObjectInputStream(iStream);
    }
    
    /**
     * Read message from the stream.
     */
    protected Object readMessage() throws IOException, UnhandledException{
		try {
			Object message = iStream.readObject();
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug(ToStringBuilder.reflectionToString("Received message: " + message));
			}
			return message;
		} catch (ClassNotFoundException e) {
			throw new UnhandledException("Class of a serialized object cannot be found", e);
		}
    }
    
}
